package com.assembly;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumer {
    private static BlockingQueue<String> queue=new ArrayBlockingQueue<>(5);

    /**
     * BlockingQueue接口有以下阻塞队列的实现：
     * FIFO 队列：LinkedBlockingQueue、ArrayBlockingQueue (固态长度)
     * 优先级队列：PriorityBlockingQueue
     * 提供了阻塞的take()和put()方法，如果队列为空take()讲阻塞，直到队列中有内容；如果队列为满put()将阻塞，直到队列有空闲位置。
     */

    //使用BlockingQueue实现生产者消费者问题
    private static class Producer extends Thread{
        @Override
        public void  run(){
            try {
                queue.put("product");
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.print("produce ...");
        }
    }


    private static class Consumer extends Thread{
        @Override
        public void run(){
            try {
                String product=queue.take();
                System.out.println(">>>>"+product+"----");
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.print("consume...");
        }
    }


    public static void main(String[] args) {
        for (int i=0;i<2;i++){
            Producer producer=new Producer();
            producer.start();
        }

        for (int i=0;i<5;i++){
            Consumer consumer=new Consumer();
            consumer.start();
        }

        for (int i=0;i<3;i++){
            Producer producer=new Producer();
            producer.start();
        }
    }
}
